package com.lagou.rpc.provider;

import com.lagou.rpc.provider.server.RpcServer;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ServerBootstrapApplication implements CommandLineRunner {

    @Value("${rpcServer.ip}")
    private String ip;

    @Value("${rpcServer.port}")
    private int port;

    @Autowired
    private CuratorFramework zkClient;

    @Autowired
    private RpcServer rpcServer;

    public static void main(String[] args) {
        SpringApplication.run(ServerBootstrapApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        new Thread(new Runnable() {
            @Override
            public void run() {
                rpcServer.startServer(ip, port);
            }
        }).start();


        String serverPath =  "/servers/" + ip + ":" + port;

        try {
            zkClient.create()
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.EPHEMERAL)
                    .forPath(serverPath, "0".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
